package com.fow.core.platform.web.rest.exception;

import com.fow.core.platform.runtime.RuntimeEnvironment;
import com.fow.core.platform.runtime.RuntimeSettings;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.MethodArgumentNotValidException;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by greg.chen on 14-10-14.
 */
@Component
public class ErrorResponseBuilder {

    private static final Logger logger = LoggerFactory.getLogger(ErrorResponseBuilder.class);

    @Autowired
    private RuntimeSettings runtimeSettings;

    public ErrorResponse createErrorResponse(Throwable e, boolean isLog) {
        String errorMessage = ExceptionUtils.stackTrace(e);
        if(isLog)
            logger.info(errorMessage);

        ErrorResponse error = new ErrorResponse();
        error.setMessage(e.getMessage());
        error.setExceptionClass(e.getClass().getName());
       // error.setRequestId(requestContext.getRequestId());
        if (!RuntimeEnvironment.PROD.equals(runtimeSettings.getEnvironment())) {
            error.setExceptionTrace(errorMessage);
        }

        return error;
    }

    public ErrorResponse createValidationResponse(InvalidRequestException e) {
        String errorMessage = ExceptionUtils.stackTrace(e);
        logger.info(errorMessage);

        ErrorResponse response = new ErrorResponse();
        response.setErrorCode(APIErrorCode.VALIDATION_ERROR.getCode());
        response.setFieldErrors(new ArrayList<FieldError>());
        FieldError error = new FieldError();
        error.setField(e.getField());
        error.setMessage(e.getMessage());
        response.getFieldErrors().add(error);
        return response;
    }

    public ErrorResponse createValidationResponse(MethodArgumentNotValidException e) {
        String errorMessage = ExceptionUtils.stackTrace(e);
        logger.info(errorMessage);

        ErrorResponse response = new ErrorResponse();
        response.setFieldErrors(new ArrayList<FieldError>());
        response.setErrorCode(APIErrorCode.VALIDATION_ERROR.getCode());
        List<org.springframework.validation.FieldError> fieldErrors = e.getBindingResult().getFieldErrors();
        for (org.springframework.validation.FieldError fieldError : fieldErrors) {
            FieldError error = new FieldError();
            error.setField(fieldError.getField());
            error.setMessage(fieldError.getDefaultMessage());
            response.getFieldErrors().add(error);
        }
        return response;
    }

}
